//
//  RegisteViewController.m
//  ChatDemo-UI2.0
//
//  Created by li.guibin on 15/12/1.
//  Copyright © 2015年 li.guibin. All rights reserved.
//

#import "RegisteViewController.h"
#import "SN_WebViewController.h"
#import "LoginViewController.h"
#import "Web_ViewController.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import <CoreLocation/CoreLocation.h>

@interface RegisteViewController ()<UIAlertViewDelegate,CLLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *registeName;
@property (weak, nonatomic) IBOutlet UITextField *registePhoneNum;
@property (weak, nonatomic) IBOutlet UITextField *verificationCode;
@property (weak, nonatomic) IBOutlet UITextField *registePassword;
@property (weak, nonatomic) IBOutlet UITextField *comfirmPassword;
@property (weak, nonatomic) IBOutlet UIButton *verificationBtn;
@property (weak, nonatomic) IBOutlet UIButton *registeBtn;
@property (weak, nonatomic) IBOutlet UIButton *agreetServiceBtn;
@property (weak, nonatomic) IBOutlet UILabel *reGetLabel;
@property (weak, nonatomic) IBOutlet UITextField *inviteCode; //邀请码
@property (nonatomic, assign)BOOL isAgreet;

@property (nonatomic, strong) CLLocationManager *locMgr;

@end

@implementation RegisteViewController {
    
    CLLocationDegrees _lat;
    CLLocationDegrees _lon;
}

@synthesize isAgreet;

- (void)loadView {
    
    [super loadView];
    
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithOriginalName:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(backButtonTapped:)];
    
//    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [leftButton setFrame:CGRectMake(0, 0, 30, 25)];
//    [leftButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
//    [leftButton addTarget:self action:@selector(backButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = left;
}

- (void)backButtonTapped:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.translucent = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.autoresizesSubviews = YES;
    
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
    }
    
    self.inviteCode.secureTextEntry = NO;
    
    _verificationBtn.layer.borderWidth = 1;
    _verificationBtn.layer.cornerRadius = 3;
    _verificationBtn.layer.borderColor = [UIColor colorWithHexString:@"#fb524a"].CGColor;
    
    _registeBtn.layer.cornerRadius = 4.0f;
    [_registeBtn addTarget:self action:@selector(registe:) forControlEvents:UIControlEventTouchUpInside];
    
    
    //数据限制
    _registeName.delegate=self;
    [_registeName addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    _registePhoneNum.delegate=self;
    [_registePhoneNum addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    _registePhoneNum.keyboardType=UIKeyboardTypeNumberPad;
    
    _verificationCode.delegate=self;
    [_verificationCode addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    _registePassword.delegate=self;
    [_registePassword addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    _comfirmPassword.delegate=self;
    [_comfirmPassword addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    
    [_agreetServiceBtn setImage:[UIImage imageNamed:@"weixuanzhong"] forState:UIControlStateNormal];
    isAgreet = YES;
    
//    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].enable = YES;
    
    //获取定位
    [self getUserLocation];

}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
}


- (IBAction)agreetAction:(UIButton *)sender {
    if (isAgreet)
    {
        isAgreet = NO;

        _agreetServiceBtn.selected = NO;
    }else
    {
        isAgreet = YES;

        _agreetServiceBtn.selected = YES;
        
    }
    
    
    if (_registeName.text.length > 0 && _registePhoneNum.text.length > 0 && _verificationCode.text.length > 0 && _registePassword.text.length > 0 &&_comfirmPassword.text.length > 0 && isAgreet) {
        
        _registeBtn.enabled = YES;
        _registeBtn.backgroundColor = [UIColor colorWithHexString:@"#fb524a"];
        
    }else{
        
        _registeBtn.enabled = NO;
        _registeBtn.backgroundColor = [UIColor colorWithHexString:@"#fccaca"];
    }
    
    
}

- (IBAction)readServiceAgreement:(UIButton *)sender {
    Web_ViewController * webView = [[Web_ViewController alloc]init];
    
    webView.url = @"http://api.our100.net/ServiceProtocols.aspx";
    [self.navigationController pushViewController:webView animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (IBAction)verify:(id)sender {
    
    if (_registePhoneNum.text.length != 11) {
        [Utils alertViewWithMessage:@"请填写正确手机号"];
        return;
    }
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_VerifyCode_get" forKey:@"method"];
    [dict setObject:@"0" forKey:@"Type"];
    [dict setObject:_registePhoneNum.text forKey:@"Mobile"];
    [Utils getWithparameters:dict showHUD:YES success:^(NSInteger recode, id jsonObject) {
        self->time=60;
        self->ti= [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
        
        [self.view endEditing:YES];
        
        [self showHint:@"验证码已发送,请注意查收"];
        
        self->_verificationBtn.hidden = YES;
        self->_reGetLabel.hidden = NO;
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
    
}
/**
 *  编辑人：张东海
 *  时间：2016年5月26日
 *  更改或添加内容：计时器调用方法
 *  备注：
 */

-(void)timerFireMethod:(NSTimer *)timer{
    
    
    time-=1;
    _reGetLabel.text = [NSString stringWithFormat:@"重新获取(%d)",time];
    
    if (time == 0 ) {
        
        [timer invalidate];
        _reGetLabel.hidden = YES;
        _verificationBtn.hidden = NO;
        
        timer = nil;
    }
}

- (void)getUserLocation {
    
    _locMgr = [[CLLocationManager alloc] init];
    _locMgr.delegate = self;
    _locMgr.distanceFilter = 0.1;
    _locMgr.desiredAccuracy = kCLLocationAccuracyBest;
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    
    if (status == kCLAuthorizationStatusNotDetermined) { //还未决定定位权限
        
        [_locMgr requestWhenInUseAuthorization];
    }else if (status == kCLAuthorizationStatusDenied) { //拒绝定位权限
        
        
        
    }else if (status == kCLAuthorizationStatusAuthorizedWhenInUse | status == kCLAuthorizationStatusAuthorizedAlways) {
        
        [_locMgr startUpdatingLocation];
    }
}

#pragma mark -CLLocationManagerDelegate

//获取授权状态
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            
            if ([_locMgr respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
                
                [_locMgr requestWhenInUseAuthorization];
            }
            
            break;
            
            
        default:
            break;
    }
}


//获取到位置信息
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    CLLocation *loc = [locations firstObject];
    
    CLLocationCoordinate2D cor2d = [loc coordinate];
    
    _lat = cor2d.latitude;
    _lon = cor2d.longitude;
    
}


- (void)registe:(id)sender {
    
    
    if ([[_registeName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
        
        [Utils alertViewWithMessage:@"请输入昵称"];
        return;
    }

    
    BOOL contains = [Utils stringContainsEmoji:_registeName.text];
    if (contains) {
        
        [Utils alertViewWithMessage:@"昵称中不能含有特殊字符"];
        return;
    }
    
    if (!isAgreet) {
        [Utils alertViewWithMessage:@"请先同意服务协议"];
        return;
    }
    
    if (_registePhoneNum.text.length == 0||_verificationCode.text.length == 0 ||[[_registePassword.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0|| [[_comfirmPassword.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0){
        
        [Utils alertViewWithMessage:@"请将信息填写完整"];
        return;
    }
    
    if (_registeName.text.length>8) {
        [Utils alertViewWithMessage:@"请将昵称限制在8个字以内"];
        return;
    }

    if (_registePassword.text.length < 6 || _registePassword.text.length > 16) {
        [Utils alertViewWithMessage:@"请将密码限制在6-16位以内"];
        return;
    }
    
    if (_comfirmPassword.text.length < 6 || _comfirmPassword.text.length > 16) {
        
         [Utils alertViewWithMessage:@"请将确认密码限制在6-16位以内"];
        return;
    }
    
    if (![_registePassword.text isEqualToString:_comfirmPassword.text]) {
        [Utils alertViewWithMessage:@"两次输入密码不一致"];
        return;
    }
    
    //判断是否含有标点
    NSCharacterSet *set = [NSCharacterSet punctuationCharacterSet];
    NSRange range = [_registePassword.text rangeOfCharacterFromSet:set];
    if (range.location != NSNotFound) {
        
        [Utils alertViewWithMessage:@"密码中含有标点符号"];
        return;
    }
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_user_register" forKey:@"Method"];
    [dict setObject:_verificationCode.text forKey:@"verify"];
    [dict setObject:_registePhoneNum.text forKey:@"mobile"];
    [dict setObject:_registeName.text forKey:@"username"];
    [dict setObject:[Utils MD5EncryptWith:_registePassword.text] forKey:@"userpass"];
    [dict setObject:@(_lat) forKey:@"lat"];
    [dict setObject:@(_lon) forKey:@"lng"];
    
    if (_inviteCode.text.length > 0) { //注册码
        [dict setObject:_inviteCode.text forKey:@"inviteuserid"];
    }
    
    [Utils getWithparameters:dict showHUD:YES success:^(NSInteger recode, id jsonObject) {
        NSDictionary * dict = (NSDictionary *)jsonObject;
        NSString *message = [dict objectForKey:@"re_info"];
        
        
        NSDictionary * personalImformation = [dict objectForKey:@"re_data"];
        BOOL save = [SyUserInfomation personalImformationSaveWtih:personalImformation];
        NSLog(@"save status 1 is success 0 is failture :%i",save);
        
        [_locMgr stopUpdatingLocation];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    } failure:^(NSInteger recode, NSError *error) {
        
        [_locMgr stopUpdatingLocation];
        
    }];
}
- (IBAction)backToLogin:(id)sender {
    
    for (UIViewController *vc in self.navigationController.childViewControllers) {
        
        if ([vc isKindOfClass:[LoginViewController class]]) {
            
            [self.navigationController popToViewController:vc animated:YES];
            break;
        }
    }
}

- (void)textFieldDidChange:(UITextField *)textField
{
    
    if (textField == _registeName) {
        
        if (_registeName.text.length > 8) {
            UITextRange *markedRange = [_registeName markedTextRange];
            if (markedRange) {
                return;
            }
            //Emoji占2个字符，如果是超出了半个Emoji，用15位置来截取会出现Emoji截为2半
            //超出最大长度的那个字符序列(Emoji算一个字符序列)的range
            NSRange range = [_registeName.text rangeOfComposedCharacterSequenceAtIndex:8];
            _registeName.text = [_registeName.text substringToIndex:range.location];
        }
        
    }else if (textField==_registePhoneNum)
    {
        if (textField.markedTextRange == nil && textField.text.length >11) {
            textField.text = [textField.text substringToIndex:11];

        }
    
    }else if (textField==_verificationCode)
    {
        if (textField.markedTextRange == nil && textField.text.length >6) {
            textField.text = [textField.text substringToIndex:6];
        }
    }else if (textField==_registePassword)
    {
        if (_registePassword.text.length > 16) {
            UITextRange *markedRange = [_registePassword markedTextRange];
            if (markedRange) {
                return;
            }
            //Emoji占2个字符，如果是超出了半个Emoji，用15位置来截取会出现Emoji截为2半
            //超出最大长度的那个字符序列(Emoji算一个字符序列)的range
            NSRange range = [_registePassword.text rangeOfComposedCharacterSequenceAtIndex:16];
            _registePassword.text = [_registePassword.text substringToIndex:range.location];
        }

    }else if (textField==_comfirmPassword)
    {
        if (_comfirmPassword.text.length > 16) {
            UITextRange *markedRange = [_comfirmPassword markedTextRange];
            if (markedRange) {
                return;
            }
            //Emoji占2个字符，如果是超出了半个Emoji，用15位置来截取会出现Emoji截为2半
            //超出最大长度的那个字符序列(Emoji算一个字符序列)的range
            NSRange range = [_comfirmPassword.text rangeOfComposedCharacterSequenceAtIndex:16];
            _comfirmPassword.text = [_comfirmPassword.text substringToIndex:range.location];
        }
    }
    
    if (_registeName.text.length > 0 && _registePhoneNum.text.length > 0 && _verificationCode.text.length > 0 && _registePassword.text.length > 0 &&_comfirmPassword.text.length > 0 && isAgreet) {
        
        _registeBtn.enabled = YES;
        _registeBtn.backgroundColor = [UIColor colorWithHexString:@"#fb524a"];
        
    }else{
        _registeBtn.enabled = NO;
        _registeBtn.backgroundColor = [UIColor colorWithHexString:@"#fccaca"];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    NSMutableDictionary *userinfo = [NSMutableDictionary dictionary];
    [userinfo setObject:_registePhoneNum.text forKey:@"phone"];
    [userinfo setObject:_registePassword.text forKey:@"password"];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"registerScuess" object:userinfo];
    
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}

@end
